package com.oromwin.repos.server.request.file;

import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;

import com.oromwin.repos.common.Logger;
import com.oromwin.repos.common.ReposException;
import com.oromwin.repos.common.helper.DBHelper;
import com.oromwin.repos.common.helper.FSHelper;
import com.oromwin.repos.data.AbstractReposTable;
import com.oromwin.repos.data.FileTable;
import com.oromwin.repos.data.MediaTable;
import com.oromwin.repos.server.LockObject;
import com.oromwin.repos.server.request.AbstractRequest;
import com.oromwin.repos.server.response.NormalResponse;
import com.oromwin.repos.server.response.Response;

public class DeleteFileRequest extends AbstractRequest {
    private Log log = Logger.getLog(DeleteFileRequest.class);
    private String FileId = null;
    private boolean _force = false;
    
    @Override
    public void receive(DataInputStream dis, LockObject lockObject) throws ReposException {
        try {
            synchronized (lockObject) {
                FileId = lockObject.getFileId();
                _force = dis.readBoolean();
            }
        } catch (IOException e) {
            String message = String.format("Failed to read stream, {%s}", e.getMessage());
            throw ReposException.create(log, e, message);
        }
    }

    @Override
    public Response run() throws ReposException {
        NormalResponse res = null;
        try {
            getCurrentReposTables();
            checkSameObjectExists();
            String whereClause = String.format("FileId = '%s'", FileId);
            if (_force) {
                DBHelper.deleteTable(FileTable.class, whereClause);
                FSHelper.rm(_fileTable.getFullFilepath());
            } else {
                _fileTable.setFileStatus(Boolean.TRUE);
                DBHelper.updateTable(_fileTable, whereClause);
            }
            whereClause = String.format("MediaId = '%s'", _fileTable.getMediaId());
            List<AbstractReposTable> fileTables = DBHelper.selectTable(FileTable.class, whereClause);
            int mediaFileCount = 0;
            long mediaUsedBytes = 0L;
            for (AbstractReposTable table : fileTables) {
                if (table instanceof FileTable) {
                    FileTable fileTable = (FileTable) table;
                    mediaFileCount++;
                    mediaUsedBytes += fileTable.getFileBytes();
                }
            }
            _mediaTable.setMediaUsedBytes(mediaUsedBytes);
            _mediaTable.setMediaFileCount(mediaFileCount);
            DBHelper.updateTable(_mediaTable, whereClause);
            res = new NormalResponse(true, "Succeeded to delete file");
        } catch (ReposException e) {
            res = new NormalResponse(false, e.getMessage());
        } catch (Exception e) {
            String message = String.format("Unexpected exception, {%s}", e.getMessage());
            throw ReposException.create(log, e, message);
        }
        return res;
    }

    @Override
    public void checkSameObjectExists() throws ReposException {
        // 1. 삭제될 파일이 있는지 확인
        File file = _fileTable.getFullFilepath();
        if (!FSHelper.ls(file)) {
            String message = String.format("'%s' FilePath does not exists", file);
            throw ReposException.create(log, message);
        }
    }

    @Override
    public void getCurrentReposTables() throws ReposException {
        // 1. 파일정보를 가져옴
        AbstractReposTable reposTable = null;
        String whereClause = String.format("FileId = '%s' AND FileStatus = 0", FileId);
        List<AbstractReposTable> reposTables = DBHelper.selectTable(FileTable.class, whereClause);
        if (reposTables != null && reposTables.size() == 1) {
            reposTable = reposTables.get(0);
        } else {
            String message = String.format("'%s' FileId does not exists in database, tableSize:whereClause {%d:%s}", FileId, reposTables.size(), whereClause);
            throw ReposException.create(log, message); 
        }
        if (reposTable instanceof FileTable) {
            _fileTable = (FileTable) reposTable;
        } else {
            String message = String.format("Illegal file table type, class {%s}", reposTable.getClass().toString());
            throw ReposException.create(log, message);
        }
        // 1. 미디어정보를 가져옴
        whereClause = String.format("MediaId = '%s' AND MediaStatus = 0", _fileTable.getMediaId());
        reposTables = DBHelper.selectTable(MediaTable.class, whereClause);
        if (reposTables != null && reposTables.size() == 1) {
            reposTable = reposTables.get(0);
        } else {
            String message = String.format("MediaId does not exists in database, tableSize:whereClause {%d:%s}", reposTables.size(), whereClause);
            throw ReposException.create(log, message); 
        }
        if (reposTable instanceof MediaTable) {
            _mediaTable = (MediaTable) reposTable;
        } else {
            String message = String.format("Illegal media table type, class {%s}", reposTable.getClass().toString());
            throw ReposException.create(log, message);
        }
    }

}
